﻿using log4net;
using SQLDataUploadHelper.commons.controls;
using SQLDataUploadHelper.consts;
using SQLDataUploadHelper.models.domain;
using SQLDataUploadHelper.services;
using System;
using System.Collections.Generic;
using System.Timers;
using System.Windows;
using System.Windows.Input;
using System.Windows.Forms;
using MessageBox = HandyControl.Controls.MessageBox;
using Timer = System.Timers.Timer;
using Window = System.Windows.Window;
using HandyControl.Controls;
using System.IO;
using NotifyIcon = HandyControl.Controls.NotifyIcon;

namespace SQLDataUploadHelper
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly ILog log = LogManager.GetLogger(App.LogRepository.Name, typeof(MainWindow));
        private SqlConnectConfigService mysqlConnectConfigService = new SqlConnectConfigService();
        private UploadServerConfigService uploadServerConfigService = new UploadServerConfigService();
        private SQLUploadService sqlUploadService = new SQLUploadService();
        private UploadServerConfig uploadServerConfig = new UploadServerConfig();
        private SqlConnectConfig mysqlConnectConfig = new SqlConnectConfig();
        private Timer ergodicMySqlTimer = new Timer();

        /// <summary>
        /// 构造函数
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();
            log.Info("应用启动");
        }

        /// <summary>
        /// 窗口加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void window_Loaded(object sender, RoutedEventArgs e)
        {
            mysqlConnectConfig = mysqlConnectConfigService.getOne();
            databaseConfigStackPanel.DataContext = mysqlConnectConfig;
            databasePassword.Password = mysqlConnectConfig.Password;

            serverInfoStackPanel.DataContext = uploadServerConfig;
            List<UploadServerConfig> uploadServerConfigs = uploadServerConfigService.list();
            foreach (UploadServerConfig item in uploadServerConfigs)
            {
                ServerInfoControl serverInfoControl = new ServerInfoControl();
                serverInfoControl.Id = item.Id;
                serverInfoControl.Url = item.Url;
                serverInfoControl.UserName = item.UserName;
                serverInfoControl.Password = item.Password;
                uploadUrlInfoStackPanel.Children.Insert(0, serverInfoControl);
                serverInfoControl.Click += ServerInfoControl_Click;
            }

            ergodicMySqlTimer.Interval = CommonConst.ERGODIR_MYSQL_INTERVAL;
            ergodicMySqlTimer.AutoReset = true;
            ergodicMySqlTimer.Enabled = true;
            ergodicMySqlTimer.Elapsed += new System.Timers.ElapsedEventHandler(timerUp);
            ergodicMySqlTimer.Start();
        }

        /// <summary>
        /// 服务配置信息列表点击
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="IsDelete"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void ServerInfoControl_Click(object sender, bool IsDelete = false)
        {
            ServerInfoControl? serverInfoControl = sender as ServerInfoControl;
            if (serverInfoControl == null)
            {
                return;
            }

            if (IsDelete)
            {
                uploadUrlInfoStackPanel.Children.Remove(serverInfoControl);
                uploadServerConfigService.delete(serverInfoControl.Id);
                if (serverInfoControl.Id == uploadServerConfig.Id)
                {
                    uploadServerConfig.reset();
                }
                MessageBox.Show("删除成功", "上送配置", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            else
            {
                uploadServerConfig = uploadServerConfigService.getById(serverInfoControl.Id);
                serverInfoStackPanel.DataContext = uploadServerConfig;
                uploadPasswordBox.Password = uploadServerConfig.Password;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerUp(object sender, ElapsedEventArgs e)
        {
            try
            {
                sqlUploadService.uploadAll(mysqlConnectConfig);
            }
            catch (Exception ex)
            {
                log.Error("定时事件失败:" + ex.Message);
            }
        }

        /// <summary>
        /// <param name="e"></param>
        /// 保存数据库配置按钮点击
        /// </summary>
        /// <param name="sender"></param>
        private void saveDbConfigBtn_Click(object sender, RoutedEventArgs e)
        {
            mysqlConnectConfig.Password = databasePassword.Password;
            if (mysqlConnectConfigService.update(mysqlConnectConfig))
            {
                MessageBox.Show("保存成功", "保存数据库配置", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            else
            {
                MessageBox.Show("保存失败", "保存数据库配置", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 测试连接按钮点击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void testConnectBtn_Click(object sender, RoutedEventArgs e)
        {
            mysqlConnectConfig.Password = databasePassword.Password;
            SQLErgodicService sqlErgodicService = new SQLErgodicService(mysqlConnectConfig);
            if (sqlErgodicService.TestConnect())
            {
                MessageBox.Show("连接成功", "测试连接", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            else
            {
                MessageBox.Show("连接失败", "测试连接", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 添加配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void addServerBtn_Click(object sender, RoutedEventArgs e)
        {
            uploadServerConfig.reset();
            uploadPasswordBox.Password = String.Empty;
        }

        /// <summary>
        /// 保存服务端配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void saveServerBtn_Click(object sender, RoutedEventArgs e)
        {
            bool isUpdate = uploadServerConfig.Id != -1;
            uploadServerConfig.Password = uploadPasswordBox.Password;
            uploadServerConfig = uploadServerConfigService.saveOrUpdate(uploadServerConfig);
            if (!isUpdate)
            {
                ServerInfoControl serverInfoControl = new ServerInfoControl();
                serverInfoControl.Id = uploadServerConfig.Id;
                serverInfoControl.Url = uploadServerConfig.Url;
                serverInfoControl.UserName = uploadServerConfig.UserName;
                serverInfoControl.Password = uploadServerConfig.Password;
                uploadUrlInfoStackPanel.Children.Insert(0, serverInfoControl);
                serverInfoControl.Click += ServerInfoControl_Click;
            }
            MessageBox.Show("保存成功", "保存服务配置", MessageBoxButton.OK, MessageBoxImage.Information);
        }

        #region 标题栏
        private void minimizeBtn_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }

        private void closeBtn_Click(object sender, RoutedEventArgs e)
        {
            this.Hide();
        }
        private void NotifyIcon_MouseDoubleClick(object sender, RoutedEventArgs e)
        {
            this.Show();
        }

        private void ContextMenu_MouseDown(object sender, MouseButtonEventArgs e)
        {
            this.Close();
            ergodicMySqlTimer.Stop();
        }

        private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }
        #endregion
    }
}
